package com.HW;

import java.util.Arrays;

/**
 * @ClassName : TEpidemicSpread
 * @Author : kele
 * @Date: 2023/10/29 9:19
 * @Description :
 */
public class TEpidemicSpread {

    public static void main(String[] args) {

        handle("1,0,1", "0,0,0", "1,0,1");
        handle("0,0,0", "0,0,0", "0,1,0");
        handle("0,0,0", "0,0,0", "0,0,0");


    }


    public static void handle(String... str) {

        int[][] dt = new int[str.length][str.length];

        int NoSpread = 0;
        for (int i = 0; i < str.length; i++) {
            String[] s = str[i].split(",");
            for (int j = 0; j < s.length; j++) {
                dt[i][j] = Integer.parseInt(s[j]);
                if(dt[i][j] == 1){
                    NoSpread++;
                }
            }
        }

        if(NoSpread == 0){
            System.out.println(-1);
            return;
        }


        int[][] action = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};


        int num = 0;
        while (!isAllOne(dt)) {
            boolean[][] isValid = new boolean[str.length][str.length];

            for (int i = 0; i < dt.length; i++) {
                for (int j = 0; j < dt.length; j++) {
                    if (dt[i][j] == 1 && !isValid[i][j]) {
                        isValid[i][j] = true;
                        for (int[] ac : action) {
                            int m = i + ac[0];
                            int n = j + ac[1];
                            if (m >= 0 && m < dt.length && n >= 0 && n < dt.length && dt[m][n] == 0) {
                                dt[m][n] = 1;
                                isValid[m][n] = true;
                            }
                        }
                    }else {
                        isValid[i][j] = true;
                    }

                }
            }

//            for (int[] ints : dt) {
//                System.out.println(Arrays.toString(ints));
//            }
//            System.out.println("----------------------");
            num++;

        }

        System.out.println(num);


    }

    public static boolean isAllOne(int[][] dt) {
        for (int[] ints : dt) {
            for (int anInt : ints) {
                if (anInt != 1) return false;
            }
        }
        return true;
    }
}
